package com.wx.todo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wx.todo.dao.TodoDao;
import com.wx.todo.entity.Todo;
import com.wx.todo.service.TodoService;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
  * 代办表(todo)表服务实现类
  * @author liuwenxuan
  * @TableName todo
  * @createDate 20250506.01
  */
@Service("todoService")
public class TodoServiceImpl extends ServiceImpl<TodoDao, Todo> implements TodoService {

 @Override
 public Map<String, Boolean> getMonthTodoFlag(String month) {
  LocalDate localDate = LocalDate.parse(month+"-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
  // 获取当月最后一天
  LocalDateTime firstDateTime = localDate.withDayOfMonth(1).atTime(0, 0, 0);
  LocalDateTime firstUtcDateTime = toUTC(firstDateTime);
  LocalDateTime lastDateTime = localDate.withDayOfMonth(localDate.lengthOfMonth()).atTime(23, 59, 59);
  LocalDateTime lastUtcDateTime = toUTC(lastDateTime);
  List<Todo> todos = this.list(new LambdaQueryWrapper<Todo>().between(Todo::getTodoDate, firstUtcDateTime, lastUtcDateTime));
  Map<String, Boolean> todoFlagMap = new HashMap<>();
  for (Todo todo : todos) {
   String todoDateKey = toLocal(todo.getTodoDate()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
   todoFlagMap.put(todoDateKey, true);
  }
  return todoFlagMap;
 }

 private LocalDateTime toLocal(Date date){
  ZonedDateTime zonedDateTime = date.toInstant().atZone(ZoneId.of("UTC"));
  return zonedDateTime.withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
 }


 private LocalDateTime toUTC(LocalDateTime localDateTime) {
  ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of("Asia/Shanghai"));
  return zonedDateTime.withZoneSameInstant(ZoneId.of("UTC")).toLocalDateTime();
 }
}

